﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Text;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using NetBay.Core.BusinessEntities.Historic;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.ApplicationNavigation;
using Rio.Framework.Pages.Context;
using Telerik.Windows;
using Telerik.Windows.Controls.GridView;
using GalaSoft.MvvmLight.Messaging;
using System.Collections.Generic;

namespace Rio.Framework.Pages.Controls.Historic
{
    public partial class SearchHistoric : UserControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public ObservableCollection<HistoricInformation> LastConsultations { get; set; }
        public ObservableCollection<HistoricInformation> LastSearches { get; set; }
        public ObservableCollection<HistoricInformation> SavedSearches { get; set; }

        private HistoricInformation _selectedLastConsultations;
        private HistoricInformation _selectedSavedSearches;
        private HistoricInformation _selectedLastSearches;

        public HistoricInformation SelectedLastConsultations
        {
            get { return _selectedLastConsultations; }
            set
            {
                _selectedLastConsultations = value;
                OnPropertyChanged("SelectedLastConsultations");

                LastConsultationsDisplayButton.IsEnabled = SelectedLastConsultations != null;
            }
        }

        public HistoricInformation SelectedLastSearches
        {
            get { return _selectedLastSearches; }
            set
            {
                _selectedLastSearches = value;
                OnPropertyChanged("SelectedLastSearches");

                LastSearchesDisplayButton.IsEnabled = SelectedLastSearches != null;
            }
        }

        public HistoricInformation SelectedSavedSearches
        {
            get { return _selectedSavedSearches; }
            set
            {
                _selectedSavedSearches = value;
                OnPropertyChanged("SelectedSavedSearches");

                SavedSearchesDeleteButton.IsEnabled = SelectedSavedSearches != null;
                SavedSearchesDisplayButton.IsEnabled = SelectedSavedSearches != null;
            }
        }

        public int HistoricMaxCountResultsDisplay { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="SearchHistoric"/> class.
        /// </summary>
        public SearchHistoric()
        {
            InitializeComponent();

            InitLabels();

            SettingsDomainContext settingsDomainContext = new SettingsDomainContext();
            settingsDomainContext.GetHistoricMaxCountResultsDisplay(
                delegate(InvokeOperation<int> retr)
                {
                    HistoricMaxCountResultsDisplay = retr.Value;

                    LoadHistoric();
                },
                null);

            LastConsultationsRadGridView.AddHandler(GridViewCellBase.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick_Consultation), true);
            LastSearchesRadGridView.AddHandler(GridViewCellBase.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick_Search), true);
            SavedSearchesRadGridView.AddHandler(GridViewCellBase.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick_SavedSearch), true);
        }

        /// <summary>
        /// Loads the historic.
        /// </summary>
        private void LoadHistoric(NotificationMessage n = null)
        {
            LoadLastConsultations();
            LoadLastSearches();
            LoadSavedSearches();
        }

        /// <summary>
        /// Loads the last consultations.
        /// </summary>
        private void LoadLastConsultations()
        {
            LastConsultationsRadGridView.IsBusy = true;

            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();

            var query = businessEntitiesDomainContext.GetLastConsultationsQuery(
                Constant.szGetDescription(Constant.UserActions.CONSULTATION_DOSSIER),
                GlobalWebContext.CurrentUser.UserId,
                HistoricMaxCountResultsDisplay,
                false);

            businessEntitiesDomainContext.Load<HistoricInformation>(
                query,
                delegate(LoadOperation<HistoricInformation> retr)
                {
                    if (retr.Error == null && retr.Entities != null)
                    {
                        LastConsultations = new ObservableCollection<HistoricInformation>(
                            retr.Entities
                            .OrderByDescending(item => item.ActionDate)
                            .ThenByDescending(item => item.ActionTime));

                        OnPropertyChanged("LastConsultations");
                    }

                    LastConsultationsRadGridView.IsBusy = false;
                },
                null);
        }

        /// <summary>
        /// Loads the last searches.
        /// </summary>
        private void LoadLastSearches()
        {
            LastSearchesRadGridView.IsBusy = true;

            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();

            //Get Last Searches
            var query = businessEntitiesDomainContext.GetLastConsultationsQuery(
                Constant.szGetDescription(Constant.UserActions.RECHERCHE),
                GlobalWebContext.CurrentUser.UserId,
                HistoricMaxCountResultsDisplay,
                false);

            businessEntitiesDomainContext.Load<HistoricInformation>(
                query,
                delegate(LoadOperation<HistoricInformation> retr)
                {
                    if (retr.Error == null && retr.Entities != null)
                    {
                        LastSearches = new ObservableCollection<HistoricInformation>(
                            retr.Entities
                            .OrderByDescending(item => item.ActionDate)
                            .ThenByDescending(item => item.ActionTime));

                        OnPropertyChanged("LastSearches");
                    }

                    LastSearchesRadGridView.IsBusy = false;
                },
                null);
        }

        /// <summary>
        /// Loads the saved searches.
        /// </summary>
        private void LoadSavedSearches()
        {
            SavedSearchesRadGridView.IsBusy = true;

            //Get Saved Searches
            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();
            var query = businessEntitiesDomainContext.GetLastConsultationsQuery(
                Constant.szGetDescription(Constant.UserActions.RECHERCHE),
                GlobalWebContext.CurrentUser.UserId,
                HistoricMaxCountResultsDisplay,
                true);

            businessEntitiesDomainContext.Load<HistoricInformation>(
                query,
                delegate(LoadOperation<HistoricInformation> retr)
                {
                    if (retr.Error == null && retr.Entities != null)
                    {
                        SavedSearches = new ObservableCollection<HistoricInformation>(
                            retr.Entities
                            .OrderByDescending(item => item.ActionDate)
                            .ThenByDescending(item => item.ActionTime));

                        OnPropertyChanged("SavedSearches");
                    }

                    SavedSearchesRadGridView.IsBusy = false;
                },
                null);
        }

        /// <summary>
        /// Deletes the selected savd search.
        /// </summary>
        private void DeleteSelectedSavedSearch()
        {
            if (SavedSearchesRadGridView.SelectedItems != null)
            {
                List<HistoricInformation> selectedSavedSearches = new List<HistoricInformation>(SavedSearchesRadGridView.SelectedItems.Cast<HistoricInformation>());
                BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();
                foreach (HistoricInformation SelectedSavedSearchesItem in selectedSavedSearches)
                {
                    businessEntitiesDomainContext.DeleteHistoricSearcSave(SelectedSavedSearchesItem.Identifier);
                    SavedSearches.Remove(SelectedSavedSearchesItem);
                }
            }
        }

        /// <summary>
        /// Inits the labels.
        /// </summary>
        private void InitLabels()
        {
            LastConsultationsTabItem.Header = Resx.GetLabel(ResxHistoric.HISTORIC_LAST_CONSULTATIONS);
            LastConsultationsDisplayButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DISPLAY);
            LastConsultationsRadGridView.Columns["LastConsultationsDateHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_DATE_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsHourHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_HOUR_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsOrganizationHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_ORGANIZATION_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsFolderTypeHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_FOLDERTYPE_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsNbDocsHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_NBDOCS_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsIndexHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_INDEX_HEADER);

            LastSearchesTabItem.Header = Resx.GetLabel(ResxHistoric.HISTORIC_LAST_SEARCHES);
            LastSearchesDisplayButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DISPLAY);
            LastSearchesRadGridView.Columns["LastSearchesDateHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_DATE_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesHourHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_HOUR_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesOrganizationHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_ORGANIZATION_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesFolderTypeHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_FOLDERTYPE_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesNbResultsHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_NBRESULTS_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesIndexHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_INDEX_HEADER);

            SavedSearchesTabItem.Header = Resx.GetLabel(ResxHistoric.HISTORIC_SAVED_SEARCHES);
            SavedSearchesDisplayButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DISPLAY);
            SavedSearchesDeleteButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DELETE);
            SavedSearchesRadGridView.Columns["SavedSearchesDateHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_DATE_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesHourHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_HOUR_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesOrganizationHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_ORGANIZATION_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesFolderTypeHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_FOLDERTYPE_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesNbResultsHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_NBRESULTS_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesIndexHeader"].Header = Resx.GetLabel(ResxHistoric.HISTORIC_INDEX_HEADER);
        }

        /// <summary>
        /// Called when [cell double click].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="Telerik.Windows.RadRoutedEventArgs"/> instance containing the event data.</param>
        private void OnCellDoubleClick_Consultation(object sender, RadRoutedEventArgs args)
        {
            OpenSelectedItem(SearchHistoricAction.Consultation);
        }

        /// <summary>
        /// Called when [cell double click_ search].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="Telerik.Windows.RadRoutedEventArgs"/> instance containing the event data.</param>
        private void OnCellDoubleClick_Search(object sender, RadRoutedEventArgs args)
        {
            OpenSelectedItem(SearchHistoricAction.Search);
        }

        /// <summary>
        /// Called when [cell double click_ saved search].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="Telerik.Windows.RadRoutedEventArgs"/> instance containing the event data.</param>
        private void OnCellDoubleClick_SavedSearch(object sender, RadRoutedEventArgs args)
        {
            OpenSelectedItem(SearchHistoricAction.SavedSearch);
        }

        /// <summary>
        /// Handles the Click event of the Open control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Open_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            if (b == LastConsultationsDisplayButton)
            {
                OpenSelectedItem(SearchHistoricAction.Consultation);
            }
            else if (b == LastSearchesDisplayButton)
            {
                OpenSelectedItem(SearchHistoricAction.Search);
            }
            else if (b == SavedSearchesDisplayButton)
            {
                OpenSelectedItem(SearchHistoricAction.SavedSearch);
            }
        }

        /// <summary>
        /// Opens the selected item.
        /// </summary>
        /// <param name="searchHistoricAction">The search historic action.</param>
        public void OpenSelectedItem(SearchHistoricAction searchHistoricAction)
        {
            HistoricInformation historicInformationSource = null;

            switch (searchHistoricAction)
            {
                case SearchHistoricAction.Consultation:
                    historicInformationSource = SelectedLastConsultations;
                    break;
                case SearchHistoricAction.Search:
                    historicInformationSource = SelectedLastSearches;
                    break;
                case SearchHistoricAction.SavedSearch:
                    historicInformationSource = SelectedSavedSearches;
                    if (historicInformationSource == null && SavedSearchesRadGridView.SelectedItems != null)
                    {
                        historicInformationSource = new List<HistoricInformation>(SavedSearchesRadGridView.SelectedItems.Cast<HistoricInformation>()).FirstOrDefault();
                    }
                    break;
            }

            if (historicInformationSource != null)
            {
                if (searchHistoricAction == SearchHistoricAction.Consultation)
                {
                    NavigationHelper.Instance.GetFolderLink(historicInformationSource.OrganizationId, historicInformationSource.FolderTypeId, historicInformationSource.FolderId, historicInformationSource.FolderIdDoc, true);
                }
                else
                {
                    NavigationHelper.Instance.GetSearcResultLink(historicInformationSource.OrganizationId, historicInformationSource.FolderTypeId, historicInformationSource.Indexes.ToList(), true);
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the Delete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxChildWindow L_oMessageToValidate = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxHistoric.HISTORIC_MSG_DELETE_SEARCH_SAVE), MessageBoxButtons.OkCancel, MessageBoxIcon.Warning);
            L_oMessageToValidate.Show();
            L_oMessageToValidate.Closed += (s, ev) =>
            {
                if (L_oMessageToValidate.Result == MessageBoxResult.OK)
                {
                    DeleteSelectedSavedSearch();
                }
            };
        }

        /// <summary>
        /// Called when [property changed].
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        public void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Handles the SizeChanged event of the userControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.SizeChangedEventArgs"/> instance containing the event data.</param>
        private void userControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.PreviousSize.Height > 0)
            {
                LastConsultationsRadGridView.Height = (e.NewSize.Height * LastConsultationsRadGridView.Height) / e.PreviousSize.Height;
            }
        }

        public enum SearchHistoricAction
        {
            Consultation,
            Search,
            SavedSearch
        }

    }
}
